#include "HTree.h"
#include "FrequencyTable.h"
#include "HuffmanTreeNode.h"
#include "IHTreeCallBack.h"


HTree::HTree(FrequencyTable* table)
{
	this->table = table;
	for (size_t i = 0; i < tableSize; ++i)
	{
		HuffmanTreeNode node;
		node.left = NULL;
		node.right = NULL;
		node.value = table->countForByte(i);
		node.letter = (uint8_t)i;
		queue.push(node);
	}
}


HTree::~HTree(void)
{
	if (table)
	{
		delete table;
	}
	dfs(root, HTree::nodeDeleter);
}

uint32_t HTree::getCode(uint8_t byte, size_t& bits)
{	
	return 0;
}

void  HTree::archiveByte(uint8_t byte)
{
	
}

void HTree::unArchivebyte(uint8_t byte)
{
	size_t i = 8;
	do
	{	
		--i;
		bool left = (byte & (1 << i));
		if (left && state->left)
		{
			state = state->left;
		}
		else if (!left && state->right)
		{
			state = state->right;
		}
		else
		{
			myDelegate->acceptFinishedByte(state->letter);
			state = root;
		}
		printf("%d\n", i);
	}
	while (i>0);
}

void HTree::dfs(HuffmanTreeNode* ver, CallBack helper)
{
	if (ver->left)
	{
		dfs(ver->left, helper);
	}
	if (ver->right)
	{
		dfs(ver->right, helper);
	}
	if (helper)
	{
		helper(ver);
	}
}

void HTree::nodeDeleter(HuffmanTreeNode* node)
{
	delete node;
}
